package com.csx.unionFind;

/**
 * @author 陈胤训
 * @date 2019/6/12 11:24
 * Utils: Intellij Idea
 * Description: 简单并查集
 */
public class UnionFind implements UF {

    private int[] id;

    public UnionFind(int size) {
        this.id = new int[size];
        for (int i = 0; i < id.length; i++) {
            id[i] = i;
        }
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElements(int p, int q) {
        int pId = find(p);
        int qId = find(q);
        if (pId == qId){
            return;
        }
        for (int i = 0; i < id.length; i++) {
            if (id[i] == pId){
                id[i] = qId;
            }
        }
    }

    @Override
    public int getSize() {
        return id.length;
    }

    /**
     * 查找元素p所对应的集合编号
     * @param p 元素
     * @return 编号
     */
    private int find(int p){
        if (p < 0 || p >= id.length){
            throw new IllegalArgumentException("p is out of bound.");
        }
        return id[p];
    }
}
